package com.myblog.service.impl;

import cn.hutool.core.lang.hash.Hash;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.constant.CodeType;
import com.myblog.constant.RedisHashKey;
import com.myblog.mapper.LeaveMapper;
import com.myblog.mapper.LikeMapper;
import com.myblog.mapper.UserMapper;
import com.myblog.model.Comment;
import com.myblog.model.Leave;
import com.myblog.service.LeaveService;
import com.myblog.service.LikeService;
import com.myblog.service.impl.redis.HashRedisServiceImpl;
import com.myblog.utils.DataMap;
import com.myblog.utils.FileUtilToLocal;
import com.myblog.utils.StringUtil;
import com.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class LeaveServiceImpl implements LeaveService {

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HashRedisServiceImpl hashRedisService;

    @Autowired
    private LikeService likeService;


    @Override
    public DataMap getNewLeave(Integer rows, Integer pageNum) {
        PageHelper.startPage(pageNum,rows);
        List<Leave> leaves = leaveMapper.selectAllLeaveWord();
        PageInfo pageInfo = new PageInfo<>(leaves);

        JSONArray jsonArray = new JSONArray();
        for (Leave leave : leaves) {
            JSONObject leaveJson = new JSONObject();
            leaveJson.put("id",leave.getId());
            //pagePath:在前端为"/"+pageName，因此直接传pageName
            leaveJson.put("pagePath",leave.getPageName());
            leaveJson.put("leaveWordContent",leave.getLeaveMessageContent());
            leaveJson.put("leaveWordDate",leave.getLeaveMessageDate());
            String answererName = userMapper.selectUserNameById(leave.getAnswererId());
            leaveJson.put("answerer",answererName);

            jsonArray.add(leaveJson);
        }

        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);
        return DataMap.success().setData(result);
    }

    @Override
    public DataMap getLeaveByPageName(String pageName,String userName) {
        List<Leave> leaves = leaveMapper.selectLeaveWordByPageName(pageName);
        //用于存放result
        JSONArray jsonArray = new JSONArray();
        HashMap<Integer,List<Leave>> replyMap = new HashMap<>();
        //判断是否为回复留言，实则放入replyMap
        for (Leave leaf : leaves) {
            if(leaf.getPid() != 0 && !replyMap.containsKey(leaf.getPid())){
                List<Leave> list = new ArrayList<>();
                list.add(leaf);
                replyMap.put(leaf.getPid(),list);
            }
            else if(leaf.getPid() != 0){
                List<Leave> list = replyMap.get(leaf.getPid());
                list.add(leaf);
                replyMap.put(leaf.getPid(),list);
            }
        }
        //用于存放replies
        for (Leave leave : leaves) {
            //根据pid判断留言还是回复留言
            if(leave.getPid() == 0){
                JSONObject leaveJson = new JSONObject();
                //用于存放replies
                List<JSONObject> repliesArray = new ArrayList<>();
                int isLiked = 0;
                //判断登录用户是否已经点赞过该评论
                if (userName != null) {
                    if (likeService.leaveIsLike(pageName, leave.getId(), userName)) {
                        isLiked = 1;
                    }
                }
                leaveJson.put("isLiked",isLiked);

                //pid为0，则为留言
                leaveJson.put("id",leave.getId());
                //pagePath:在前端为"/"+pageName，因此直接传pageName
                leaveJson.put("pagePath",leave.getPageName());
                leaveJson.put("leaveMessageContent",leave.getLeaveMessageContent());
                leaveJson.put("leaveMessageDate",leave.getLeaveMessageDate());
                String answererName = userMapper.selectUserNameById(leave.getAnswererId());
                //获取用户头像
                String avatarImgUrl = userMapper.selectAvatarImgUrlById(leave.getAnswererId());
                FileUtilToLocal fileUtil = new FileUtilToLocal();
                String useAvatarImgUrl = fileUtil.disposeUserImgUrl(avatarImgUrl);
                leaveJson.put("answerer",answererName);
                leaveJson.put("avatarImgUrl",useAvatarImgUrl);
                leaveJson.put("likes",leave.getLikes());
                //获取本留言的回复
                List<Leave> replies = replyMap.get(leave.getId());
                if(replies == null){
                    leaveJson.put("replies",repliesArray);
                }
                else {
                    for (Leave reply : replies) {
                        JSONObject replyJson = new JSONObject();
                        replyJson.put("id", reply.getId());
                        //获取答主信息
                        String answererNameReply = userMapper.selectUserNameById(reply.getAnswererId());
                        replyJson.put("answerer", answererNameReply);
                        //获取回复人信息
                        String respondentName = userMapper.selectUserNameById(reply.getRespondentId());
                        replyJson.put("respondent", respondentName);
                        replyJson.put("leaveMessageContent", reply.getLeaveMessageContent());
                        replyJson.put("leaveMessageDate", reply.getLeaveMessageDate());
                        repliesArray.add(replyJson);
                    }
                    leaveJson.put("replies",repliesArray);
                }
                jsonArray.add(leaveJson);
            }
        }

        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        return DataMap.success().setData(result);
    }

    @Override
    public DataMap publishLeaveMessage(String leaveMessageContent, String pageName, int answerId) {
        //新建对象将获得的参数传入
        Leave leave = new Leave();
        leave.setPageName(pageName);
        leave.setLeaveMessageContent(leaveMessageContent);
        leave.setAnswererId(answerId);
        //发布留言默认pid为0
        leave.setPid(0);
        //发布留言默认respondent=answer
        leave.setRespondentId(answerId);
        //获得发布留言的时间
        TimeUtil timeUtil = new TimeUtil();
        String publishDate = timeUtil.getFormatDateForFive();
        leave.setLeaveMessageDate(publishDate);
        //发布留言默认likes = 0
        leave.setLikes(0);
        //发布留言默认未读
        leave.setIsRead((byte) 1);

        leaveMapper.addLeaveWord(leave);
        //用户总未读信息+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.ALL_USER_NEWS,1);
        //用户未读留言数量+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.LEAVE_NEW_NUM,1);
        DataMap flushed = this.getLeaveByPageName(pageName,userMapper.selectUserNameById(answerId));
        return flushed;
    }

    @Override
    public DataMap ReplyLeaveMessage(String leaveMessageContent, String pageName, int answerId, String pIdString, String respondentName) {
        //新建对象将获得的参数传入
        Leave leave = new Leave();
        leave.setPageName(pageName);
        //处理传过来的留言内容
        if(leaveMessageContent.charAt(0) == '@'){
            leaveMessageContent =leaveMessageContent.substring(respondentName.length()+1,leaveMessageContent.length());
        }
        else{
            leaveMessageContent =leaveMessageContent;
        }
        leave.setLeaveMessageContent(leaveMessageContent);
        leave.setAnswererId(answerId);
        //回复留言默认pid为回复留言的id
        String pIdS = pIdString.substring(1,pIdString.length());
        Integer pId = Integer.parseInt(pIdS);
        leave.setPid(pId);
        //回复留言通过回复人的姓名查找
        Integer respondentId = userMapper.selectUserIdByUsername(respondentName);
        leave.setRespondentId(respondentId);
        //获得回复留言的时间
        TimeUtil timeUtil = new TimeUtil();
        String replyDate = timeUtil.getFormatDateForFive();
        leave.setLeaveMessageDate(replyDate);
        //回复留言默认likes = 0
        leave.setLikes(0);
        //回复留言默认未读
        leave.setIsRead((byte) 1);

        leaveMapper.addLeaveWord(leave);

        //用户总未读信息+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.ALL_USER_NEWS,1);
        //用户未读留言数量+1
        hashRedisService.hashIncrement(String.valueOf(answerId), RedisHashKey.LEAVE_NEW_NUM,1);

        JSONObject result = new JSONObject();
        String answerName = userMapper.selectUserNameById(answerId);
        result.put("answerer",answerName);
        result.put("respondent",respondentName);
        result.put("leaveMessageDate",replyDate);
        result.put("leaveMessageContent",leaveMessageContent);

        return DataMap.success().setData(result);
    }

    @Override
    public DataMap getUserLeaveWord(Integer rows, Integer pageNum, Integer userId) {
        PageHelper.startPage(pageNum,rows);
        List<Leave> leaves = leaveMapper.selectLeaveWordByRespondentId(userId);
        PageInfo pageInfo = new PageInfo<>(leaves);

        JSONArray jsonArray = new JSONArray();
        for (Leave leave : leaves) {
            JSONObject leaveJson = new JSONObject();
            leaveJson.put("id",leave.getId());
            //获取父id
            leaveJson.put("pId",leave.getPid());
            //pageName
            leaveJson.put("pageName",leave.getPageName());
            leaveJson.put("leaveMessageDate",leave.getLeaveMessageDate());
            String answererName = userMapper.selectUserNameById(leave.getAnswererId());
            leaveJson.put("answerer",answererName);
            //获取已读信息
            leaveJson.put("isRead",leave.getIsRead());
            jsonArray.add(leaveJson);
        }
        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);
        //获取该用户的未读评论
        result.put("msgIsNotReadNum",leaveMapper.selectNotReadNumByRespondentId(userId));
        return DataMap.success().setData(result);
    }

    @Override
    public DataMap setAllLeaveIsRead(Integer respondentId) {
        leaveMapper.updateAllLeaveIsReadByRespondentId(respondentId);
        return DataMap.success();
    }

}
